from appuifw import app
from e32 import Ao_lock,ao_sleep
from os import path
from codecs import open
from struct import unpack
from sysinfo import active_profile,signal_bars
from audio import Sound
from envy import set_app_hidden,set_app_system
from appswitch import switch_to_bg,fg_appname
from appuifw2 import Text as Text2,app as app2
from sys import path as pathsys

app_lock=Ao_lock()
settingsfile=u'c:\\data\\others\\netalarm.cfg'
wave=u'c:\\data\\sounds\\netalarm.mp3'
numerotacche=1
numerointervallo=30
autostart=1
inferiore=0
testo=Text2(skinned=1)
switch_to_bg(fg_appname())
set_app_system(1)
set_app_hidden(1)

def hide(): switch_to_bg(app.title)
	
def exit_key_handler():
	app_lock.signal()
	app.set_exit()

def carica_settings():
	global numerotacche,numerointervallo,autostart
	if path.exists(settingsfile):
		readsettings=open(settingsfile,'rb').readlines()[0]
		try: numerotacche,numerointervallo,autostart=unpack('>hhh',readsettings)
		except: pass

def verifica_segnale():
	global inferiore
	if active_profile()=='general':
		if signal_bars() < numerotacche:
			if not inferiore:
				inferiore=1
				try: s.play()
				except: inferiore=0
		else: inferiore=0
	ao_sleep(numerointervallo)
	#s.close()

def subthread():
	global inferiore
	inferiore=0
	while 1: verifica_segnale()

s=Sound.open(wave)
app.exit_key_handler=hide
carica_settings()
app.title=u'NetAlarm Server'
#app.menu=[(u'Esci',exit_key_handler)]
app2.menu_key_text=u''
app2.exit_key_text=u'Close'
testo.set(u'Running...')
testo.read_only = True
app.body=testo
subthread()
app_lock.wait()